import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ChatRoomClient {
    public static void main(String[] args) {
        try (Socket socket = new Socket("127.0.0.1", 18989)) {
            Sender sender = new Sender(socket);
            sender.start();

            Receiver receiver = new Receiver(socket);
            receiver.setDaemon(true);
            receiver.start();

            sender.join();

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class Receiver extends Thread {
    private final Socket socket;

    public Receiver(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (Scanner input = new Scanner(System.in);
             OutputStream ops = socket.getOutputStream()) {
            try (PrintStream ps = new PrintStream(ops)) {
                while (true) {
                    System.out.print("请输入：\n\t");
                    String message = input.nextLine();
                    if ("exit".equals(message)) {
                        break;
                    }

                    ps.println(message);
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

class Sender extends Thread {
    private final Socket socket;

    public Sender(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (InputStream is = socket.getInputStream()) {
            try (Scanner input = new Scanner(is)) {
                while (input.hasNextLine()) {
                    String message = input.nextLine();
                    System.out.println(message);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}